import {
	isLoginToken,
	saveToken
} from "../tools/token.js"
export default {
	namespaced: true,
	state: {
		token: isLoginToken(),
		userData: {},
		goodDetial: {},
		carData:[],
		orderData:[],
		addressDate:[],
		addressId:'',
		orderId:''
	},
	actions: {
		async getUserData({
			commit
		}, vue) {
			if (vue.tools.isToken()) {
				const result = await uni.$u.api.reqUserData()
				if (result) {
					commit('SETUSERDATA', result)
					return true
				}
				commit('SETUSERDATA', '')
				commit('SETTOKEN', '')
			}
		},
		async getGoodsDetial({
			commit
		}, {id,boolen}) {
			return await uni.$u.api.reqRequsetDetial(id) || {}
		},
		async getCatListDData({commit}){
			const {data} =  await uni.$u.api.reqShopCartList()
			commit('SETSHOPCARLIST',data)
			return true
		},
		async getChangeCarNum({commit},{id,num}){
			const result = await uni.$u.api.reqChangeCarNum(id,{num})
			return result
		},
		async getOrdersData({commit}){
			const {address,carts} =  await uni.$u.api.reqOrdersDetial()
			commit('SETORDERDATA',carts)
			commit('SETADDRESSDATA',address)
			return true
		},
		async getSumbitOrder({state,commit},ids){
			let result;
			if(!ids){
				result = await uni.$u.api.reqSumbitOreder({address_id:state.addressId}) 
				if(!state.addressId)return uni.showToast({
					title:'请选择地址',
					icon:'none'
				})
			}
			
			if(ids || result.id){
				const {qr_code_url} = await uni.$u.api.reqPayData(ids ? ids : result.id)
				result ? commit('SETORDERID',result.id) : ''
				return qr_code_url
			}
			return false
		}
	},
	mutations: {
		SETUSERDATA(state, value) {
			state.userData = value
			uni.setStorageSync('userData', JSON.stringify(state.userData))
		},
		SETTOKEN(state, value) {
			state.token = value
			saveToken(state.token)
		},
		SETGOODLDATA(state,value) {
			state.goodDetial = value
		},
		SETSHOPCARLIST(state,value){
			state.carData = value
		},
		SETORDERDATA(state,value){
			state.orderData = value
		},
		SETADDRESSDATA(state,value){
			state.addressDate = value
		},
		SETADDRESSID(state,value){
			state.addressId = value
		},
		SETORDERID(state,value){
			state.orderId = value
		}
	},
	getters:{
		like_goods(state){
			return state.goodDetial.like_goods ? state.goodDetial.like_goods  : []
		},
		goods(state){
			return state.goodDetial.goods ? state.goodDetial.goods : {}
		},
		sumPirce(state){
			return state.orderData.reduce((value, item) => {
				if (item.is_checked == 1) {
					return value += item.goods.price * item.num
				}
				return value
			}, 0)
		}
	}
}
